#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe 
#
# Distributed under terms of the MIT license.

import re
import logging
import urllib
import requests
from bs4 import BeautifulSoup
from proxy_manager.core import ProxyHost
from proxy_manager.resource.base import BaseProxyResource

logger = logging.getLogger(__name__)

class ProxyResource(BaseProxyResource):
    api = 'http://dps.kuaidaili.com/api/getdps/?orderid={}&num={}&format=json&sep=1'

    def __init__(self,  orderid, auth=None, scheme='http', limit=10):
        self.orderid = orderid
        self.auth = auth
        self.url = self.api.format(orderid, limit)
        self.scheme=scheme

    def download(self):
        data = requests.get(self.url).json()
        logger.info(data['msg'])
        proxy_list = data['data']['proxy_list'] 
        result = []
        for proxy in proxy_list:
            ip, port = proxy.split(":")
            result.append(ProxyHost(ip=ip, port=port, scheme=self.scheme, auth=self.auth))
        return result
        
    def get_proxies(self):
        try:
            data = self.download()
            return data
        except Exception as e:
            logger.error(e, exc_info=True)
            raise e



